/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef OHOS_GRPC_NODE_HTTP2_UTILS_H
#define OHOS_GRPC_NODE_HTTP2_UTILS_H
#include "ohos_log.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <string>
#include <sys/socket.h>

std::vector<std::string> resolveTxt(const std::string &domain) {
    std::vector<std::string> txtRecords;
    struct addrinfo hints, *res, *p;
    int status;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    if ((status = getaddrinfo(domain.c_str(), NULL, &hints, &res)) != 0) {
        LOGE("getaddrinfo error:%s", gai_strerror(status));
        return txtRecords;
    }
    for (p = res; p != NULL; p = p->ai_next) {
        char host[NI_MAXHOST];
        if (getnameinfo(p->ai_addr, p->ai_addrlen, host, sizeof host, NULL, 0, NI_NAMEREQD) == 0) {
            LOGE("resolveTxt host %s", host);
            txtRecords.push_back(host);
        }
    }
    freeaddrinfo(res);
    return txtRecords;
}

char *dnsLookupIPv4(const std::string &hostname) {
    struct addrinfo hints, *res, *p;
    int status;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    if ((status = getaddrinfo(hostname.c_str(), NULL, &hints, &res)) != 0) {
        LOGE("getaddrinfo error:%s", gai_strerror(status));
        return "";
    }
    char *result;
    for (p = res; p != NULL; p = p->ai_next) {
        struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
        char ipstr[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &(ipv4->sin_addr), ipstr, sizeof ipstr);
        result = ipstr;
        break;
    }
    LOGE("dnsLookupIPv4 ip %s",result);
    freeaddrinfo(res);
    return result;
}

int timeDifference(time_t timestamp1, time_t timestamp2) {
    return std::abs(timestamp1 - timestamp2);
}

#endif // OHOS_GRPC_NODE_HTTP2_UTILS_H
